package io.github.shenbinglife.springboot2.layui.admin.service.impl;

import io.github.shenbinglife.springboot2.layui.admin.dao.OrgDao;
import io.github.shenbinglife.springboot2.layui.admin.entity.Org;
import io.github.shenbinglife.springboot2.layui.admin.entity.User;
import io.github.shenbinglife.springboot2.layui.common.model.TreeNode;
import io.github.shenbinglife.springboot2.layui.common.service.impl.BaseService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrgService extends BaseService<Org, OrgDao> {


    public List<TreeNode<Long>> getOrgTree(Long parentId, boolean recursive) {
        List<Org> orgs = baseDao.findByParentIdOrderByOrdered(parentId);
        List<TreeNode<Long>> treeList = orgs.stream()
                .map(it -> it.toTreeNode(parentId))
                .collect(Collectors.toList());
        if (recursive) {
            for (TreeNode<Long> treeNode : treeList) {
                treeNode.setChildren(getOrgTree(treeNode.getId(), true));
            }
        }
        return treeList;
    }

    public void deleteWithChildren(Long id) {
        List<Org> orgs = baseDao.findByParentIdOrderByOrdered(id);
        for (int i = 0; i < orgs.size(); i++) {
            deleteWithChildren(orgs.get(i)
                    .getId());
        }
        deleteById(id);
    }

    @Override
    public void deleteById(Long id) {
        baseDao.removeRelationByOrgId(id);
        super.deleteById(id);
    }

    public void removeRelationByUserId(Long userId) {
        baseDao.removeRelationByUserId(userId);
    }

    public void addUserToOrg(Long orgId, Long... userIds) {
        baseDao.addUserToOrg(orgId, userIds);
    }

    public List<Org> getUserOrgs(Long userId) {
        return baseDao.findOrgsByUserId(userId);
    }

    public void addUsersToOrg(Long orgId, Long... userIds) {
        baseDao.addUserToOrg(orgId, userIds);
    }

    public void removeUsersFromOrg(Long orgId, Long... userIds) {
        for (Long userId : userIds) {
            baseDao.removeUserFromOrg(orgId, userId);
        }
    }

    public List<User> getOrgUsers(Long orgId) {
        return baseDao.findUserByOrgId(orgId);
    }

    public Page<User> getPageRoleUsers(Long orgId, String keyword, int page, Integer limit) {
        return baseDao.findUsersByOrgIdWithPagination(orgId, keyword, PageRequest.of(page, limit, Sort.by("account")));
    }
}
